


from django.shortcuts import render, HttpResponse
import random
from utils.tencent.sms import send_sms_single
from django.conf import settings
from .qcloud_cos import client
import re
from tracer.settings import BUCKET
# def index(request):
#     if request.method=='POST':
#         file = request.FILES.get('file')
#         if file:
#             file_name = file.name
#             response = client.put_object(
#                 Bucket=BUCKET,
#                 Body=file,
#                 Key=file_name,
#                 StorageClass='STANDARD',
#                 EnableMD5=False
#             )
#             print(response['ETag'])
#             return HttpResponse('上传成功')
#         else:
#             return HttpResponse('上传失败')
#
#     return render(request,'index.html')
def send_sms(request):
    """ 发送短信
        ?tpl=login  -> 548762
        ?tpl=register -> 548760
    """
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    phone = request.GET.get('phone')
    ret = re.match(r"^1[35789]\d{9}$", phone)
    if not ret:
        return HttpResponse('手机号码格式 错误')
    if not template_id:
        return HttpResponse('模板不存在')
    else:
        code = random.randrange(1000, 9999)
        conn = get_redis_connection("default")
        conn.set(phone, code, ex=60)
        res = send_sms_single(phone, template_id, [code, ])
        if res['result'] == 0:
            return HttpResponse('成功')
        else:
            return HttpResponse(res['errmsg'])

from django_redis import get_redis_connection
from .forms import RegisterModelForm
def register(request):
    form = RegisterModelForm()
    if request.method == 'POST':
        code = request.POST.get('code')
        phone = request.POST.get('mobile_phone')
        conn = get_redis_connection("default")
        value = conn.get(phone)
        if value:
            if int(value) == int(code):
                form_set = RegisterModelForm(data=request.POST)
                if form_set.is_valid():
                    form_set.save()
                    return HttpResponse('注册成功')
                else:
                    return HttpResponse(form_set.errors)

        return HttpResponse('验证码失效或错误')
    return render(request, 'app01/register.html', {'form': form})

from django.http import JsonResponse
def demo2(request):
    return render(request, 'demo2.html')

from django.conf import settings
def cos_credential(request):
    # ⽣成⼀个临时凭证，并给前端返回
    # 1. 安装⼀个⽣成临时凭证python模块 pip install -U qcloud-python-sts
    # 2. 写代码
    from sts.sts import Sts

    config = {
        # 临时密钥有效时⻓，单位是秒（30分钟=1800秒）
        'duration_seconds': 1800,
        # 固定密钥 id
        'secret_id': settings.TENCENT_COS_ID,
        # 固定密钥 key
        'secret_key': settings.TENCENT_COS_KEY,
        # 换成你的 bucket
        'bucket': "tracer-1301482037",
        # 换成 bucket 所在地区
        'region': "ap-beijing",
    # 这⾥改成允许的路径前缀，可以根据⾃⼰⽹站的⽤户登录态判断允许上传的具体路径
    # 例⼦： a.jpg 或者 a/* 或者 * (使⽤通配符*存在重⼤安全⻛险, 请谨慎评估使
    #⽤)
    'allow_prefix': '*',
    # 密钥的权限列表。简单上传和分⽚需要以下的权限，其他权限列表请看
    #https: // cloud.tencent.com / document / product / 436 / 31923
    'allow_actions': [
        'name/cos:PostObject',
        # 'name/cos:DeleteObject',
        # "name/cos:UploadPart",
        # "name/cos:UploadPartCopy",
        # "name/cos:CompleteMultipartUpload",
        # "name/cos:AbortMultipartUpload",
        "*",
    ],
    }
    sts = Sts(config)
    result_dict = sts.get_credential()
    return JsonResponse(result_dict)